<template>
  <BreadcrumbBar
    parent-label="Authority Management"
    child-label="Sort Management"
  ></BreadcrumbBar>

  <div class="tips">
    新建分类以系统为一级分类，二级分类为默认设定分类，无法新建和修改，二级分类以下可自定义
  </div>

  <div class="tree">
    <!-- 瀑布流布局组件 -->
    <Waterfall
      :list="(sortTree as any)"
      :width="470"
      :animationDelay="160"
      :breakpoints="{
        1700: { rowPerView: 3 },
        1350: { rowPerView: 2 },
        950: { rowPerView: 1 },
      }"
    >
      <template #item="{ item, index }">
        <el-card style="min-width: 420px; margin: 20px" :key="index">
          <template #header>
            <div style="font-weight: bold; color: #606266">
              {{ item.label }} 相关分类
            </div>
          </template>

          <el-tree
            :data="[item]"
            node-key="id"
            :default-expand-all="true"
            :expand-on-click-node="false"
            :highlight-current="true"
            class="custom-tree"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div v-show="node.level === 1" class="tag oneLevel">
                  <i
                    class="icon-apps-fill"
                    style="font-size: 20px; color: #f89898"
                  ></i>
                  <div class="tagLabel">{{ node.label }}</div>
                </div>

                <div v-show="node.level === 2" class="tag twoLevel">
                  <i
                    class="icon-sort-desc"
                    style="font-size: 20px; color: #eebe77"
                  ></i>
                  <div class="tagLabel">{{ node.label }}</div>
                </div>

                <div v-show="node.level > 2" class="tag otherLevel">
                  <i
                    class="icon-price-tag-3-line"
                    style="font-size: 18px; color: #909399"
                  ></i>
                  <div class="tagLabel">{{ node.label }}</div>
                </div>

                <div>
                  <el-popconfirm
                    title="确认删除"
                    placement="left"
                    @confirm="deleteSort"
                  >
                    <template #reference>
                      <el-button
                        v-show="node.level != 2"
                        v-once-click
                        size="small"
                        type="danger"
                        plain
                        :icon="Delete"
                        @click="getDeleteSortIdList(data)"
                      >
                      </el-button>
                    </template>
                  </el-popconfirm>

                  <el-button
                    v-show="node.level != 2"
                    v-once-click
                    size="small"
                    color="#626aef"
                    plain
                    :icon="Edit"
                    @click="openUpdateSortDialog(data.value, data.label)"
                  >
                  </el-button>

                  <el-button
                    v-show="node.level > 1"
                    v-once-click
                    size="small"
                    color="#529b2e"
                    plain
                    :icon="Plus"
                    @click="openCreateSortDialog(data.value)"
                  >
                  </el-button>

                  <el-tooltip
                    effect="dark"
                    content="为所有分类添加根系统编码 (对原来的旧数据进行补充)"
                    placement="top"
                  >
                    <el-button
                      v-show="node.level === 1"
                      v-once-click
                      size="small"
                      color="#F56C6C"
                      plain
                      :icon="Refresh"
                      @click="sortAddRootSystemCode(data.value)"
                    >
                    </el-button>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </template>
    </Waterfall>
  </div>

  <!--  -->
  <!-- 创建分类描述对话框 -->
  <el-dialog
    v-model="createSortDialogVisible"
    title="新增分类描述对话框"
    draggable
    width="800px"
    :before-close="sortDialogCloseHandler"
  >
    <div class="inputForm">
      <div class="inputItem">
        <div class="label">上级分类详情:</div>
        <div class="value">
          <el-cascader
            v-model="sortParentId"
            :options="sortTree"
            :props="{ checkStrictly: true }"
            placeholder="请选择上级分类"
            disabled
            size="large"
            style="width: 100%; height: 100%"
          />
        </div>
      </div>

      <div class="inputItem">
        <div class="label">新增分类名称:</div>
        <div class="value">
          <el-input
            v-model="sortDescription"
            placeholder="请输入分类名称"
            clearable
            maxlength="20"
            show-word-limit
            style="width: 100%; height: 100%"
          />
        </div>
      </div>

      <div class="inputItem">
        <div class="label">分类的优先级:</div>
        <div class="value">
          <el-select
            v-model="sortWeight"
            placeholder="Select"
            size="large"
            style="width: 100%; height: 100%"
          >
            <el-option
              v-for="item in 20"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
      </div>
    </div>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="sortDialogCloseHandler"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="createSortDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 更新分类描述对话框 -->
  <el-dialog
    v-model="updateSortDialogVisible"
    title="更新分类描述对话框"
    draggable
    width="800px"
    :before-close="sortDialogCloseHandler"
  >
    <div class="inputForm">
      <div class="inputItem">
        <div class="label">新增分类名称:</div>
        <div class="value">
          <el-input
            v-model="sortDescription"
            placeholder="请输入分类名称"
            clearable
            maxlength="20"
            show-word-limit
            style="width: 100%; height: 100%"
          />
        </div>
      </div>

      <div class="inputItem">
        <div class="label">分类的优先级:</div>
        <div class="value">
          <el-select
            v-model="sortWeight"
            placeholder="Select"
            size="large"
            style="width: 100%; height: 100%"
          >
            <el-option
              v-for="item in 20"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
      </div>
    </div>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="sortDialogCloseHandler"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="updateSortDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { Delete, Edit, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
// @ts-ignore
import { Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import { storeToRefs } from 'pinia'
import { createSortApi, updateSortApi, deleteSortApi } from '@/request/api/sort'
import { sortAddRootSystemCodeApi } from '@/request/api/rootSystem'
import { useSortTreeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'

import BreadcrumbBar from '@/components/BreadcrumbBar/BreadcrumbBar.vue'

const { sortTree, originData } = storeToRefs(useSortTreeStore())
const { openAlert } = useMessageAlertStore()

onMounted(() => {
  useSortTreeStore().getSortList()
})

// 为所有分类添加根系统编码 (对原来的旧数据进行补充)
const sortAddRootSystemCode = async (sortId: string) => {
  const res = await sortAddRootSystemCodeApi({ id: sortId, systemCode: null })
  if (res.code !== 200) return openAlert.error(res.message)

  ElMessage.success(res.message)
}

// 当前编辑的分类id
const currentSortId = ref<string>('')
// 分类上级id，（分类上级选择器值）
const sortParentId = ref<string[]>([])
// 分类描述
const sortDescription = ref<string>('')
// 分类权重
const sortWeight = ref<number>(0)

// 创建分类
const createSort = async () => {
  if (sortDescription.value.length === 0)
    return openAlert.warning('分类描述不能为空！')
  if (sortParentId.value.length === 0)
    return openAlert.warning('分类上级不能为空！')

  const s = sortParentId.value
  let pId: string = s[s?.length - 1]

  const res = await createSortApi(sortDescription.value, pId, sortWeight.value)
  if (res.code !== 200) return openAlert.error(res.message)
  sortDescription.value = ''
  ElMessage.success('创建成功！')
  useSortTreeStore().getSortList()
}

// 修改分类信息
const updateSort = async () => {
  if (sortDescription.value.length === 0)
    return openAlert.warning('分类描述不能为空！')

  const res = await updateSortApi(
    sortDescription.value,
    currentSortId.value,
    sortWeight.value
  )
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('修改成功！')
  useSortTreeStore().getSortList()
}

// 创建分类信息对话框
const createSortDialogVisible = ref<boolean>(false)
// 修改分类信息对话框
const updateSortDialogVisible = ref<boolean>(false)

// 对话框关闭取消回调
const sortDialogCloseHandler = () => {
  updateSortDialogVisible.value = false
  createSortDialogVisible.value = false
  sortParentId.value = []
  currentSortId.value = ''
  sortDescription.value = ''
  sortWeight.value = 0
}

const openCreateSortDialog = (sortId: string) => {
  createSortDialogVisible.value = true
  sortParentId.value = useSortTreeStore().findParentValues(
    sortTree.value,
    sortId
  )
}
// 确认回调
const createSortDialogConfirmHandler = () => {
  createSort()
  sortDialogCloseHandler()
}

const openUpdateSortDialog = (sortId: string, desc: string) => {
  currentSortId.value = sortId
  sortDescription.value = desc
  sortWeight.value = originData.value.filter(
    (item) => item.id === sortId
  )[0].weight
  updateSortDialogVisible.value = true
}
// 确认回调
const updateSortDialogConfirmHandler = () => {
  updateSort()
  sortDialogCloseHandler()
}

// 要删除的分类id列表
const deleteSortIdList = ref<string[]>([])
// 提取出要删除的分类id列表
const getDeleteSortIdList = (list: any) => {
  let lt = [list.value]
  if (list.children) fn(list.children)
  deleteSortIdList.value = lt

  function fn(l: any[]) {
    for (const item of l) {
      lt.push(item.value)
      if (item.children) fn(item.children)
    }
  }
}
// 删除分类
const deleteSort = async () => {
  const res = await deleteSortApi(deleteSortIdList.value)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('删除成功！')
  deleteSortIdList.value = []
  useSortTreeStore().getSortList()
}
</script>

<style lang="less" scoped>
.label {
  font-size: 15px;
  font-weight: bold;
  color: #606266;
  padding: 0 10px;
}

.tips {
  font-size: 14px;
  font-weight: bold;
  color: #918f8f;
  padding: 10px 10px;
}

.tree {
  box-shadow: 0 0 1px 2px #ececec;
  border-radius: 6px;
  // padding: 20px 10px;
  margin: 10px;
  overflow: auto;
  // display: flex;
  // flex-wrap: wrap;
  width: calc(100% - 20px);
  // width: 100%;
  user-select: none;
}

/deep/ .custom-tree {
  .el-tree-node__content {
    padding-top: 5px; /* 设置上边距 */
    padding-bottom: 5px; /* 设置下边距 */
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  > .tag {
    display: flex;
    align-items: center;

    > .tagLabel {
      padding-left: 2px;
    }
  }
  > .oneLevel {
    font-weight: bold;
    font-size: 15px;
    color: #606266;
  }

  > .twoLevel {
    font-weight: bold;
    color: #73767a;
  }

  > .otherLevel {
    font-weight: bold;
    color: #909399;
  }
}

.inputForm {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 0;
  align-items: center;

  > .inputItem {
    height: 40px;
    width: 350px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    margin-right: 20px;
    background-color: #cfcdcd21;

    > .label {
      min-width: 120px;
      height: 100%;
      font-size: 15px;
      font-weight: bold;
      color: #606266;
      user-select: none;
      background-color: #c8e0e4;
      display: flex;
      justify-content: center;
      align-items: center;
      padding-left: 5px;
      padding-right: 5px;
    }

    > .value {
      flex: 1;
      display: flex;
      height: 100%;
      border-radius: 4px;
      box-shadow: 0 0 1px 1px #bdbdbd8a;
    }
  }
}
</style>
